package com.jsnider.timelineplanner;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.view.Menu;

public class MainActivity extends Activity {

	private TableLayout taskTableLayout;
	private EditText taskEditText; 
	private EditText timeEditText;
	public ImageButton removeTask;
	final static String TASK_NUM = "com.jsnider.timelineplanner.TASK_NUM";
	private SharedPreferences savedSearches;
	public int task_num;
	public boolean edit_true;
	public int edit_index;
	public View view_to_edit;
	public ArrayList<Event> tasks = new ArrayList<Event>();

	//TODO: set max number of tasks to 20
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		savedSearches = getSharedPreferences("tasks", MODE_PRIVATE);
		
		SharedPreferences.Editor preferencesEditor = savedSearches.edit();
		//preferencesEditor.clear();
		//preferencesEditor.commit();
		
		boolean restart_true;
		
		taskTableLayout = (TableLayout) findViewById(R.id.taskTableLayout);
		taskEditText = (EditText) findViewById(R.id.taskEditText);
		timeEditText = (EditText) findViewById(R.id.timeEditText);
		
		Button enterButton = (Button) findViewById(R.id.enterButton);
		enterButton.setOnClickListener(enterButtonListener);
		
		Button startButton = (Button) findViewById(R.id.startButton);
		startButton.setOnClickListener(startButtonListener);
		ImageButton removeTask = (ImageButton) findViewById(R.id.removeTask);
		
		task_num = 0;
		edit_true = false;
		
		//debug();
		refresh();
	}
	
	public void startTimeScreen()
	{
		Intent intent = new Intent(MainActivity.this, TimeScreen.class);
		startActivity(intent);

	}
	
	public String getFinishTime()
	{
		Time now = new Time();
		Time finish = new Time();
		now.setToNow();
		
		int hr, mins, carry = 0, pm = 0;
		hr = now.hour;
		mins = now.minute;
		
		//TODO: i think here something goes wrong if atually am
		if(hr > 11) {
			pm = 1;
			hr = hr%12;
		}
		
		int task_time = 0;
		int hours, minutes;
		for (int i = 0; i < tasks.size(); i++) {
			task_time += tasks.get(i).getTime();
		}
		hours = (int) task_time / 60;
		minutes = task_time % 60;
		//TODO:time will be lost if hours is over 12

		//hr = Integer.parseInt(now.format("%k"));
		//mins = Integer.parseInt(now.format("%M"));
		
		int fin_min, fin_hr;
		
		if(mins+minutes > 59) {
			carry++;
			fin_min = (mins+minutes)%60;
		} else {
			fin_min = mins+minutes;
		}
		if(hr+hours+carry > 12) {
			if(pm == 1)
				pm =0;
			fin_hr = (hr+hours+carry)%12;
		} else {
			fin_hr = hr+hours+carry;
		}
			
		String am = "";
		if(pm == 1)
			am = "pm";
		if(pm == 0)
			am = "am";
		
		//hr += hours;
		//mins += minutes;

		//return hr+":"+mins+"," + hours+":"+minutes+","+fin_hr+":"+fin_min;
		return fin_hr+":"+ ((fin_min < 10) ? "0"+fin_min : fin_min) + am;
	}
	
	//uses shared preferences to make view
	public void refresh()
	{
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View newTaskView;
		TextView taskTextView;
		TextView timeTextView;
		Button newEditButton;
		Button newRemoveTask;
		Button upButton;
		Button downButton;
		TextView indexTextView;
		
		taskTableLayout.removeAllViews();
		
		for (int index = 0; index < tasks.size(); ++index)
		{   
            String task = tasks.get(index).getTask();
      		int time = (int) tasks.get(index).getTime();
      		
			newTaskView = inflater.inflate(R.layout.new_task_view, null);
			
			newTaskView.setTag(index);

			taskTextView = (TextView) newTaskView.findViewById(R.id.taskTextView);
			timeTextView = (TextView) newTaskView.findViewById(R.id.timeTextView);
			
			newEditButton =
					(Button) newTaskView.findViewById(R.id.newEditButton);
			newEditButton.setOnClickListener(editButtonListener);
			
			newRemoveTask = (Button) newTaskView.findViewById(R.id.removeTask);
			newRemoveTask.setOnClickListener(removeButtonListener);
			
			upButton = (Button) newTaskView.findViewById(R.id.upArrow);
			upButton.setOnClickListener(upButtonListener);
			downButton = (Button) newTaskView.findViewById(R.id.downArrow);
			downButton.setOnClickListener(downButtonListener);
			
			indexTextView = (TextView) newTaskView.findViewById(R.id.index);
			indexTextView.setText(index+1+"");
				
			taskTextView.setText(task);
			timeTextView.setText(time+"");
			
			taskTableLayout.addView(newTaskView,index);
		}
	
	}
	
	public void debug()
	{
		Event temp;
		temp = new Event("test_1", 
		           2);	
		tasks.add(temp);
		
		temp = new Event("test_2", 
		           2);	
		tasks.add(temp);
		
		temp = new Event("test_3", 
		           2);	
		tasks.add(temp);
//		temp = new Event("test_4", 
//		           55);	
//		tasks.add(temp);
//		temp = new Event("test_5", 
//		           55);	
//		tasks.add(temp);
//		temp = new Event("test_6", 
//		           55);	
//		tasks.add(temp);
//		temp = new Event("test_7", 
//		           55);	
//		tasks.add(temp);
//		temp = new Event("test_8", 
//		           55);	
//		tasks.add(temp);
//		temp = new Event("test_9", 
//		           55);	
//		tasks.add(temp);
//		temp = new Event("test_10", 
//		           55);	
//		tasks.add(temp);
//		temp = new Event("test_11", 
//		           55);	
//		tasks.add(temp);
		
	}
	
	
	//saves task to timeline
	public OnClickListener enterButtonListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{	
			Event temp;
			int time_int;
			String time_str = timeEditText.getText().toString();
			String task = taskEditText.getText().toString();
			
			if(task.length() > 0 &&
					time_str.length() > 0)
			{
				try {
					time_int = Integer.parseInt(time_str);
				} catch (NumberFormatException e) {
					
					Toast.makeText(v.getContext(), "Enter a number", Toast.LENGTH_LONG).show();
//					AlertDialog.Builder builder = 
//		               new AlertDialog.Builder(MainActivity.this);
//
//		            builder.setTitle("Input error"); 
//		            builder.setPositiveButton("Ok", null); 
//		            builder.setMessage("Please enter a number into the time field");
//		            AlertDialog errorDialog = builder.create();
//		            errorDialog.show();
		            return;
				}
				
				if(!(time_int >= 1 && time_int <= 60))
				{
					Toast.makeText(v.getContext(), "Enter a number between 1 and 60", Toast.LENGTH_LONG).show();

//					AlertDialog.Builder builder = 
//		               new AlertDialog.Builder(MainActivity.this);
//
//		            builder.setTitle("Input error"); 
//		            builder.setPositiveButton("Ok", null); 
//		            builder.setMessage("Enter a time between 1 and 60");
//		            AlertDialog errorDialog = builder.create();
//		            errorDialog.show();
		            return;
						
				}
				
				if(edit_true == false)
				{
					temp = new Event(task, 
					           time_int);	
					tasks.add(temp);
				} else {
					temp = tasks.get(edit_index);
					
					temp.setTask(task);
					temp.setTime(time_int);
					
					edit_index = -1;
					edit_true = false;
				}
				
				refresh();
				
				taskEditText.setText("");
				timeEditText.setText("");

			} else {
				Toast.makeText(v.getContext(), "Enter input", Toast.LENGTH_LONG).show();

//				
//				AlertDialog.Builder builder =
//					new AlertDialog.Builder(MainActivity.this);
//				
//				builder.setTitle("Input error");
//				builder.setPositiveButton("Ok", null);
//				builder.setMessage("Please enter valid input");
//				
//				AlertDialog errorDialog = builder.create();
//				errorDialog.show();	
			}	
		}
	};
	
	//start the timeline 
	OnClickListener startButtonListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
		      if(tasks.size() < 1) {
		    	 // makeToast();
		    	  Toast.makeText(v.getContext(), "Enter tasks", Toast.LENGTH_LONG).show();
		    	  return;
		      }
			
			AlertDialog.Builder builder = 
					new AlertDialog.Builder(MainActivity.this);

			builder.setTitle("Finished?");
			builder.setPositiveButton("Yes", 
					new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int button)
				{				
				      SharedPreferences.Editor preferencesEditor = savedSearches.edit();
//				      preferencesEditor.clear();
//				      preferencesEditor.commit();
				      
				      //load tasks into preferencesEditor
				      for(int i = 0; i < tasks.size(); i++)
				      {
				    	  preferencesEditor.putString(
				    			  i+"",
				    			  tasks.get(i).getTask() + ":" +
				    			  tasks.get(i).getTime()); // store the updated preferences
				      }
				      preferencesEditor.commit();
					
						Intent intent = new Intent(MainActivity.this, TimeScreen.class);
						Bundle b = new Bundle();
						b.putInt(TASK_NUM, tasks.size());
						b.putString("TYPE", "CREATE");
						intent.putExtras(b);
						startActivity(intent);
					//finish();
				}
			}
					);
			builder.setCancelable(true);
			builder.setNegativeButton("No", null);
			
			String finish = getFinishTime();

			builder.setMessage("Ready to go?\n" + "You will finish around " + finish);

			AlertDialog confirmDialog = builder.create();
			confirmDialog.show();
		}
	};
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		 SharedPreferences.Editor preferencesEditor = savedSearches.edit();
//	      preferencesEditor.clear();
//	      preferencesEditor.commit();
	      
		 savedInstanceState.putInt("SIZE", tasks.size());
		 
	      //load tasks into preferencesEditor
	      for(int i = 0; i < tasks.size(); i++)
	      {
	    	  preferencesEditor.putString(
	    			  i+"",
	    			  tasks.get(i).getTask() + ":" +
	    			  tasks.get(i).getTime()); // store the updated preferences
	      }
	      preferencesEditor.commit();
	      
	      super.onSaveInstanceState(savedInstanceState);

	}
	
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		
		task_num = savedInstanceState.getInt("SIZE");
		
		Event temp;
		String temp_str;
		String temp_array[];
		for (int index = 0; index < task_num; ++index)
		{
			temp_str = savedSearches.getString(index+"", null);
			temp_array = temp_str.split(":");
			temp = new Event(temp_array[0], 
					Integer.parseInt(temp_array[1]));
			tasks.add(temp);
		}
		
		refresh();

		
	}
	
	public String convertToString(Tasks tasks) {
		String text = "";
		Event temp;
		for(int i = 0; i < tasks.task_list.size(); i++)
		{
			temp = tasks.task_list.get(i);
			text += "(" + i + "," + temp.getTime() + ","
					+ temp.getTask() + ")";
		}
		return text;
		
	}
	
	public OnClickListener editButtonListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			edit_true = true;
			
			TableRow buttonTableRow = (TableRow) v.getParent();
			int index = Integer.parseInt(buttonTableRow.getTag().toString());
			
			edit_index = index;

			TextView taskTextView = 
				(TextView) buttonTableRow.findViewById(R.id.taskTextView);
			TextView timeTextView = 
					(TextView) buttonTableRow.findViewById(R.id.timeTextView);
			
			String task = taskTextView.getText().toString();
			String time = timeTextView.getText().toString();
			
			
			taskEditText.setText(task);
			timeEditText.setText(time);
		}
	};
	
	public OnClickListener upButtonListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			TableRow buttonTableRow = (TableRow) v.getParent().getParent();
			int index = Integer.parseInt(buttonTableRow.getTag().toString());
			
			if(edit_true == true)
				resetEdit(buttonTableRow);
			
			if(tasks.size() <= 1)
				return;
			
			if(index == 0)
				return;
			
			Event swap_1 = tasks.get(index - 1);		
			Event swap_2 = tasks.get(index);

			tasks.remove(index);
			tasks.remove(index -1);
			
			tasks.add(index - 1, swap_2);
			tasks.add(index, swap_1);
			
			refresh();
		}
	};
	
	public OnClickListener downButtonListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			TableRow buttonTableRow = (TableRow) v.getParent().getParent();
			int index = Integer.parseInt(buttonTableRow.getTag().toString());
			
			if(edit_true == true)
				resetEdit(buttonTableRow);
			
			if(tasks.size() <= 1)
				return;
			
			if(index == tasks.size()-1)
				return;
			
			Event swap_1 = tasks.get(index);		
			Event swap_2 = tasks.get(index+1);

			tasks.remove(index);
			tasks.remove(index);
			
			tasks.add(index, swap_2);
			tasks.add(index+1, swap_1);
			
			refresh();
		}
	};
	
	public void resetEdit(TableRow buttonTableRow)
	{
		TextView taskTextView = 
			(TextView) buttonTableRow.findViewById(R.id.taskTextView);
		TextView timeTextView = 
				(TextView) buttonTableRow.findViewById(R.id.timeTextView);
		taskEditText.setText("");
		timeEditText.setText("");
	
		edit_index = -1;
		edit_true = false;	

	}
	
	public OnClickListener removeButtonListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			String task;
			int index;
			TableRow buttonTableRow = (TableRow) v.getParent();
			//TextView taskTextView = (TextView) buttonTableRow.findViewById(R.id.taskTextView);
			//task = (String) taskTextView.getText();
			taskTableLayout.removeView(buttonTableRow);
			
			index = Integer.parseInt(buttonTableRow.getTag().toString());
			tasks.remove(index);
			
			if(edit_true == true)
				resetEdit(buttonTableRow);
			
			refresh();
//			SharedPreferences.Editor preferencesEditor = savedSearches.edit();
//			preferencesEditor.remove(task);
//			preferencesEditor.commit();
//			task_num--;

		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
